import React, { Component } from "react";
import { login, register } from "../api/index";
import { Notify } from "react-vant";

export default class Login extends Component {
  state = {
    username: "",
    password: "",
    data: [],
  };
  username(e) {
    this.setState({
      username: e.target.value,
    });
  }
  password(e) {
    this.setState({
      password: e.target.value,
    });
  }
  //登录
  login = () => {
    login({
      username: this.state.username,
      password: this.state.password,
    }).then((res) => {
      console.log(res);
      this.setState({
        data: res.data.data,
      });
      // 跳转
      if (res.data.code === 0) {
        localStorage.setItem("token", res.data.token);
        localStorage.setItem("img", res.data.data.img);
        localStorage.setItem("username", res.data.data.username);
        Notify.show({ type: "success", message: res.data.msg });
        this.props.history.push({
          pathname: "/home/homepage",
          state: this.state.data,
        });
      } else {
        Notify.show({ type: "danger", message: res.data.msg });
      }
    });
  };
  //注册
  register = () => {
    register({
      username: this.state.username,
      password: this.state.password,
    }).then((res) => {
      console.log(res);
      if (res.data.code === 2) {
        Notify.show({ type: "danger", message: res.data.msg });
      } else {
        Notify.show({ type: "success", message: res.data.msg });
      }
    });
  };
  render() {
    return (
      <div className="login">
        <h2>登录春雨医生</h2>
        <div className="loginmain">
          <input
            type="text"
            className="loginipt"
            placeholder="用户名:"
            onChange={(e) => {
              this.username(e);
            }}
          />
          <input
            type="password"
            className="loginipt"
            placeholder="密码:"
            onChange={(e) => {
              this.password(e);
            }}
          />
          <div className="loginbtns">
            <button onClick={() => this.login()}>登录</button>
            <button onClick={() => this.register()}>注册</button>
          </div>
        </div>
      </div>
    );
  }
}
